﻿using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.EMMA;
using DocumentFormat.OpenXml.Spreadsheet;
using FileManager.Model;
using FileManager.Util;
using FileManager.ViewModel;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.GridFS;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;


namespace FileManager
{
    /// <summary>
    /// BookWindow.xaml 的交互逻辑
    /// </summary>
    public partial class BookWindow : Window
    {
        private BookWindowViewModel model { get; set; }

        public BookWindow()
        {
            InitializeComponent();
            model = new BookWindowViewModel(this);
            DataContext = model;
            model.Banks = new System.Collections.ObjectModel.ObservableCollection<string>() {
                "本单位","建设银行","农业银行","工商银行","江南银行","邮政储蓄","江苏银行","中国银行","交通银行"
            };
            model.SelectedBank = model.Banks[0];
        }
        private bool mouseDown = false;
        private System.Windows.Point? _lastMousePosition;
        private void picBox_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (e.MouseDevice.LeftButton == MouseButtonState.Pressed)
            {
                if (!_lastMousePosition.HasValue)
                {
                    _lastMousePosition = e.GetPosition(this);
                    return;
                }
                // 计算从上一个位置到当前位置的距离  
                double dx = Math.Abs(e.GetPosition(this).X - _lastMousePosition.Value.X);
                double dy = Math.Abs(e.GetPosition(this).Y - _lastMousePosition.Value.Y);
                double xmove = dx * 100 / picBox.Width;
                double ymove = dy * 100 / picBox.Height;
                if (Math.Abs(xmove) >= 1)
                {
                    dx = e.GetPosition(this).X - _lastMousePosition.Value.X;
                    double hsnum = MainPlane.HorizontalOffset - dx;
                    if (hsnum >= 0 && hsnum <= MainPlane.MaxWidth)
                    {
                        MainPlane.ScrollToHorizontalOffset(hsnum);
                    }
                    if (hsnum > MainPlane.MaxWidth)
                    {
                        MainPlane.ScrollToRightEnd();
                    }
                    if (hsnum < 0)
                    {
                        MainPlane.ScrollToLeftEnd();
                    }
                    _lastMousePosition = e.GetPosition(this);

                }
                if (Math.Abs(ymove) >= 1)
                {
                    dy = e.GetPosition(this).Y - _lastMousePosition.Value.Y;
                    double vsnum = MainPlane.VerticalOffset - dy;
                    if (vsnum >= 0 && vsnum <= MainPlane.MaxHeight)
                    {
                        MainPlane.ScrollToVerticalOffset(vsnum);
                    }
                    if (vsnum > MainPlane.MaxHeight)
                    {
                        MainPlane.ScrollToBottom();
                    }
                    if (vsnum < 0)
                    {
                        MainPlane.ScrollToTop();
                    }
                    _lastMousePosition = e.GetPosition(this);
                }
                //Console.WriteLine($"Mouse moved: Dx={dx}, Dy={dy}");

                //// （可选）如果你想要得到总的移动距离（不考虑方向），你可以使用Pythagorean定理  
                //double totalDistance = Math.Sqrt(dx * dx + dy * dy);
                //Console.WriteLine($"Total distance moved: {totalDistance}");
            }
        }

        private void picBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            _lastMousePosition = e.GetPosition(this);
        }

        private void MainPlane_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _lastMousePosition = null;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var saveDir = new DirectoryInfo(Directory.GetCurrentDirectory() + "\\book\\");
            Dictionary<string, FileInfo> pairs = new Dictionary<string, FileInfo>();
            foreach (var file in saveDir.GetFiles())
            {
                if (!pairs.ContainsKey(HashHelper.GetFileHash256(file.FullName)))
                {

                    pairs.Add(HashHelper.GetFileHash256(file.FullName), file);
                }
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {

        }

        private void ExportBookXls_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(string.Join(',', "单位名称", "委托开始时间", "委托结束时间", "委托签署时间", "银行", "备注"));

            // 先对数据进行筛选，只保留相同Dwmch中SignDate最大的记录
            var filteredData = model.LetterDatas
                .GroupBy(d => d.Dwmch) // 按单位名称分组
                .Select(g => g.OrderByDescending(d => d.SignDate).First()); // 在每组中选择SignDate最大的记录
            foreach (var d in filteredData)
            {
                sb.AppendLine(string.Join(',', d.Dwmch, d.StarTime, d.EndTime, d.SignDate, d.Bank, String.Join('|', d.Tag)));
            }

            // 写入到临时文件  
            string tempFilePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "MyTempFile_" + Guid.NewGuid().ToString()+".csv");
            File.WriteAllText(tempFilePath, sb.ToString());

            // 打开文件  
            try
            {
                Process.Start(new ProcessStartInfo(tempFilePath) { UseShellExecute = true });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"无法打开文件: {ex.Message}");
            }
        }

        private void Jump_Click(object sender, RoutedEventArgs e)
        {
            model.JumpVis = true;

        }

        private void UpdateMongo_Click(object sender, RoutedEventArgs e)
        {
            IMongoClient client = new MongoClient(Config.MongoUrl);
            MongoDB.Driver.IMongoDatabase database = client.GetDatabase(Config.DataBase);
            MongoDB.Driver.IMongoCollection<MongoDB.Bson.BsonDocument> collection = database.GetCollection<MongoDB.Bson.BsonDocument>(Config.BookCollection);
            var bson = collection.FindAsync<BsonDocument>("{}").Result;

            // 自定义 Bucket 名称（images）
            var options = new GridFSBucketOptions { BucketName = Config.BucketName };
            var gridFsBucket = new GridFSBucket(database, options);

            string basePath = AppDomain.CurrentDomain.BaseDirectory;
            Debug.WriteLine("Hello Word");

            foreach (var item in model.LetterDatas.AsEnumerable())
            {
                LetterData letter = (LetterData)item;
                Debug.WriteLine(item.Path);
                string fileName = System.IO.Path.GetFileName(item.Path);
                string relPath = System.IO.Path.GetRelativePath(basePath, item.Path);
                BsonDocument document = letter.ToBsonDocument();
                document["Path"] = relPath;

                try
                {
                    using (var stream = File.OpenRead(relPath))
                    {
                        if (FindFileByHash(gridFsBucket, letter.Hash, out ObjectId id))
                        {
                            // 删除旧版本
                            gridFsBucket.DeleteAsync(id).Wait();
                        }

                        id = gridFsBucket.UploadFromStream(
                           filename: fileName,
                           stream,
                           new GridFSUploadOptions
                           {
                               Metadata = document
                           }
                        );
                        // 上传文件并返回ID（可用于引用）
                        Console.WriteLine($"Uploaded file ID: {id}");
                    }
                    // 查询文件
                    var files = gridFsBucket.Find(new BsonDocument()).ToList();
                    foreach (var file in files)
                    {
                        Console.WriteLine($"{file.Filename} - Size: {file.Length} bytes");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }
                Debug.WriteLine(relPath);

            }
        }

        public static bool FindFileByHash(GridFSBucket gridFsBucket, string hash, out ObjectId Id)
        {
            var filter = new BsonDocument {
                { "metadata.Hash", hash } // 确保 metadata 中存了 hash 字段
            };
            var exit=gridFsBucket.Find(filter).FirstOrDefault();
            if (exit != null)
            {
                Id = exit.Id;
                return true;

            }
            Id = default;
            return false;
        }
        }

}